# 1.按照要求，使用rnn完成股票预测（10分）
# (1)数据处理
import matplotlib.pyplot as plt
import numpy as np
from keras import Sequential, layers, optimizers, losses

data = np.loadtxt('data-02-stock_daily.csv', delimiter=',')
# ①读取数据，进行倒序处理
data = data[::-1]

# ②数据进行归一化处理
from sklearn.preprocessing import MinMaxScaler

data = MinMaxScaler().fit_transform(data)
# ③将数据全部列作为x，最后一列作为y
# ④设置数据前7天作为x，第8天作为y
x_data = []
y_data = []

for i in range(len(data) - 7):
    x_data.append(data[i:i + 7])
    y_data.append(data[i + 7, -1])
x_data = np.array(x_data)
y_data = np.array(y_data)

from sklearn.model_selection import train_test_split

# ⑤将数据按照7:3切分
X_train, X_test, y_train, y_test = train_test_split(x_data, y_data, train_size=0.7, shuffle=False)

# (2)模型处理
# ①创建模型
model = Sequential([
    layers.LSTM(units=256, return_sequences=True),
    layers.LSTM(units=256, return_sequences=False),
    layers.Dense(1)
])
# model.build(input_shape=(None, 7, 5))
# model.summary()
# ②使用lstm进行处理
# ③编译模型，使用mse，配合adam优化器
model.compile(optimizer=optimizers.Adam(0.01), loss=losses.mse, metrics='mse')
model.fit(X_train, y_train, batch_size=100, epochs=100)
# ④预测结果
res = model.predict(X_test)
print()
# ⑤将实际值和预测值结果可视化
plt.plot(res, c='r')
plt.plot(y_test, c='g')
plt.show()
